#!/bin/bash

# SmartInput SSL证书生成脚本
# 生成本地CA根证书和服务器证书，解决HTTPS连接问题

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CERTS_DIR="$PROJECT_ROOT/certs"
SERVER_DIR="$PROJECT_ROOT/server"

print_message $BLUE "🔐 SmartInput SSL证书生成工具"
print_message $BLUE "================================"

# 创建证书目录
mkdir -p "$CERTS_DIR"

# 检查OpenSSL
if ! command -v openssl &> /dev/null; then
    print_message $RED "❌ OpenSSL未安装，请先安装OpenSSL"
    exit 1
fi

print_message $YELLOW "📝 生成SSL配置文件..."

# 创建CA配置文件
cat > "$CERTS_DIR/ca.conf" << EOF
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_ca
prompt = no

[req_distinguished_name]
C = CN
ST = Beijing
L = Beijing
O = SmartInput Development
OU = Development Team
CN = SmartInput Local CA
emailAddress = dev@smartinput.local

[v3_ca]
basicConstraints = critical,CA:TRUE
keyUsage = critical,keyCertSign,cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
EOF

# 创建服务器证书配置文件
cat > "$CERTS_DIR/server.conf" << EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = CN
ST = Beijing
L = Beijing
O = SmartInput Development
OU = Development Team
CN = localhost
emailAddress = dev@smartinput.local

[v3_req]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation,digitalSignature,keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
IP.2 = ::1
IP.3 = 192.168.3.17
EOF

print_message $YELLOW "🔑 生成CA根证书..."

# 生成CA私钥
openssl genrsa -out "$CERTS_DIR/ca-key.pem" 4096

# 生成CA根证书
openssl req -new -x509 -days 3650 -key "$CERTS_DIR/ca-key.pem" -out "$CERTS_DIR/ca-cert.pem" -config "$CERTS_DIR/ca.conf"

print_message $GREEN "✅ CA根证书生成完成"

print_message $YELLOW "🔑 生成服务器证书..."

# 生成服务器私钥
openssl genrsa -out "$CERTS_DIR/server-key.pem" 2048

# 生成服务器证书签名请求
openssl req -new -key "$CERTS_DIR/server-key.pem" -out "$CERTS_DIR/server.csr" -config "$CERTS_DIR/server.conf"

# 使用CA签名服务器证书
openssl x509 -req -days 365 -in "$CERTS_DIR/server.csr" -CA "$CERTS_DIR/ca-cert.pem" -CAkey "$CERTS_DIR/ca-key.pem" -CAcreateserial -out "$CERTS_DIR/server-cert.pem" -extensions v3_req -extfile "$CERTS_DIR/server.conf"

print_message $GREEN "✅ 服务器证书生成完成"

# 复制证书到项目根目录和服务器目录
cp "$CERTS_DIR/server-cert.pem" "$PROJECT_ROOT/cert.pem"
cp "$CERTS_DIR/server-key.pem" "$PROJECT_ROOT/key.pem"

if [ -d "$SERVER_DIR" ]; then
    cp "$CERTS_DIR/server-cert.pem" "$SERVER_DIR/cert.pem"
    cp "$CERTS_DIR/server-key.pem" "$SERVER_DIR/key.pem"
fi

# 清理临时文件
rm -f "$CERTS_DIR/server.csr"

print_message $GREEN "🎉 SSL证书生成完成！"
print_message $BLUE "================================"

print_message $YELLOW "📁 证书文件位置："
echo "  CA根证书: $CERTS_DIR/ca-cert.pem"
echo "  服务器证书: $CERTS_DIR/server-cert.pem"
echo "  服务器私钥: $CERTS_DIR/server-key.pem"
echo "  已复制到项目根目录: cert.pem, key.pem"

print_message $YELLOW "🔧 下一步操作："
echo "1. 安装CA根证书到操作系统和浏览器"
echo "2. 在手机上安装CA根证书"
echo "3. 重启SmartInput服务器"

print_message $BLUE "📖 安装说明："
echo "Windows: 双击 ca-cert.pem，安装到'受信任的根证书颁发机构'"
echo "macOS: 双击 ca-cert.pem，添加到钥匙串，设置为'始终信任'"
echo "Linux: sudo cp ca-cert.pem /usr/local/share/ca-certificates/smartinput-ca.crt && sudo update-ca-certificates"
echo "Android: 设置 > 安全 > 加密与凭据 > 安装证书 > CA证书"
echo "iOS: 通过邮件或AirDrop发送证书，设置 > 通用 > 关于本机 > 证书信任设置"

print_message $GREEN "🔗 验证方法："
echo "安装完成后，访问 https://localhost:3001/health 应该显示安全连接" 